/**
 * @date 2006-5-11 11:33:32
 *
 */
package org.nanhill.commons.io;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;

/**
 * @author alin [xalinx at gmail dot com]
 * 
 */
public abstract class IoKit {

	private static final int DEFAULT_BUFFER_SIZE = 8192;

	/**
	 * Copy the contents of the given InputStream to the given OutputStream.
	 * 
	 * @param in
	 *            the stream to copy from
	 * @param out
	 *            the stream to copy to
	 * @return the number of bytes copied
	 * @throws IOException
	 *             in case of I/O errors
	 */
	public static void copy(InputStream in, OutputStream out)
			throws IOException {
		copy(in, out, DEFAULT_BUFFER_SIZE);
	}

	public static void copy(InputStream in, OutputStream out, int bufferSize)
			throws IOException {
		byte[] buffer = new byte[bufferSize];
		int bytesRead = -1;
		while ((bytesRead = in.read(buffer)) != -1) {
			out.write(buffer, 0, bytesRead);
		}
	}

	private static final int DEFAULT_BYTE_ARRAY_SIZE = 1024;

	/**
	 * Read string from given InputStream with specified character set.
	 * 
	 * @param in
	 * @param charSet
	 * @return
	 * @throws IOException
	 */
	public static String readString(InputStream in, String charSet)
			throws IOException {
		return readString(in, charSet, DEFAULT_BYTE_ARRAY_SIZE);
	}

	/**
	 * Read string from given InputStream with specified character set.
	 * 
	 * @param in
	 * @param charSet
	 * @return
	 * @throws IOException
	 */
	public static String readString(InputStream in, String charSet,
			int byteBufferSize) throws IOException {
		ByteArrayOutputStream output = new ByteArrayOutputStream(byteBufferSize);
		copy(in, output);
		return new String(output.toByteArray(), charSet);
	}
}
